﻿using SSC.Models;
using SSC.ViewModels;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace SSC.Views
{
    /// <summary>
    /// ucDataMonitor.xaml 的交互逻辑
    /// </summary>
    public partial class ucDataMonitor : UserControl
    {
        private bool isPopupOpen = false;  // 标志位，防止重复打开/关闭
        public ucDataMonitor()
        {
            InitializeComponent();
        }

        private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // 获取 DataGrid 的选中项
            var dataGrid = sender as DataGrid;
            if (dataGrid?.SelectedItem is SlotModel selectedSlot)
            {
                // 创建 wdPart 窗口实例
                var partWindow = new wdPart
                {
                    // 将选中的槽号传递给 wdPart 的 DataContext
                    DataContext = new PartViewModel
                    {
                        SelectedSlot = selectedSlot.SlotNumber.ToString()
                    }
                };

                // 显示窗口
                partWindow.ShowDialog();
            }
        }

        private async void Slot_MouseEnter(object sender, MouseEventArgs e)
        {
            // 如果 Popup 已经打开，就不再做任何操作
            if (isPopupOpen) return;

            var slotControl = sender as ucSlotControl;
            if (slotControl == null) return;

            // 延迟打开，避免立刻触发 MouseLeave
            await Task.Delay(500);

            // 如果此时鼠标已经离开了槽体控件，则不再打开
            if (!slotControl.IsMouseOver) return;

            // 设置内容
            txtPopupSlotCode.Text = $"槽号: {slotControl.SlotCode}";
            txtPopupConductivity.Text = $"电导率：{GetConductivity(slotControl.SlotCode)}";
            txtPopupPh.Text = $"PH值：{GetPhValue(slotControl.SlotCode)}";
            // 设置 Popup 的显示目标和方式
            slotInfoPopup.PlacementTarget = slotControl; // 指定目标控件
            slotInfoPopup.Placement = PlacementMode.Right; // 避免遮挡原控件
            slotInfoPopup.IsOpen = true;
            isPopupOpen = true;
            // 自动延迟关闭
            await Task.Delay(3000);
            slotInfoPopup.IsOpen = false;  
            isPopupOpen = false;
        }

        private void Slot_MouseLeave(object sender, MouseEventArgs e)
        {
            // 确保关闭 Popup
            if (isPopupOpen)
            {
                slotInfoPopup.IsOpen = false;  // 直接关闭 Popup
                isPopupOpen = false;  // 更新标志位
            }
        }

        // 获取电导率的方法
        private string GetConductivity(string slotCode)
        {
            return "0.8";
        }

        // 获取pH值的方法
        private string GetPhValue(string slotCode)
        {
            return "7.5";
        }
    }
}
